<template>
  <div>
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item prop="name">
        <el-input v-model="dataForm.title" placeholder="标题" clearable>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle(0)">新增</el-button>
        <el-button type="info" @click="dataForm = {}">重置</el-button>
        <el-button type="info" @click="refresh">刷新</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据 -->
    <el-table
      :data="dataList"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column prop="title" label="标题" width="100"> </el-table-column>
      <el-table-column prop="content" label="正文" align="center">
      </el-table-column>
      <el-table-column prop="img" label="推送图片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            style="width: 150px; height: 100px"
            :preview-src-list="[scope.row.imageUrl]"
          />
          <el-image v-else>
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="imageUrl" label="图片链接"> </el-table-column>
      <el-table-column prop="linkUrl" label="原文链接"> </el-table-column>
      <el-table-column prop="isActive" label="是否展示">
        <template slot-scope="scope">
          <span v-if="scope.row.isActive === 1">是</span>
          <span v-if="scope.row.isActive === 0">否</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id, scope.row)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="page"
      :page-sizes="[5, 10, 20, 50, 100]"
      :page-size="size"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 新增和修改的弹层 -->
    <el-dialog
      :title="!formData.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible="visible"
      @close="closeForm"
    >
      <el-form
        :rules="rules"
        :model="formData"
        ref="formData"
        @keyup.enter.native="dataFormSubmit()"
        label-width="100px"
      >
        <el-form-item prop="title" label="标题">
          <el-input v-model="formData.title" placeholder="标题" clearable>
          </el-input>
        </el-form-item>

        <el-form-item prop="content" label="正文">
          <el-input
            type="textarea"
            v-model="formData.content"
            placeholder="正文"
          ></el-input>
        </el-form-item>
        <el-form-item prop="imageUrl" label="图片链接">
          <el-upload
            ref="upload"
            action=""
            :on-change="onUploadChange"
            :auto-upload="false"
            :show-file-list="true"
            :file-list="fileList"
          >
            <el-button>上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="linkUrl" label="原文链接">
          <el-input
            v-model="formData.linkUrl"
            placeholder="原文链接（非必填）"
          ></el-input>
        </el-form-item>
        <el-form-item prop="isActive" label="是否展示">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="formData.isActive"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeForm">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataListSelections: [],
      dataList: [],
      selectedOptions: [],
      // 修改/新增的弹窗数据
      formData: {},
      visible: false,
      dataForm: {
        title: ''
      },
      dataListLoading: false,
      // 分页
      page: 1,
      size: 10,
      total: 0,
      fileList: [],
      rules: {
        title: [
          {
            required: true,
            message: '请输入标题'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入正文'
          }
        ]
      }
    }
  },
  methods: {
    onUploadChange(file) {
      this.fileList = [file]
    },
    getDataList() {
      this.$http({
        url: this.$http.adornUrl('/sys/homepagePush/list'),
        method: 'get',
        params: {
          ...this.dataForm,
          page: this.page,
          size: this.size
        }
      }).then(({ data }) => {
        this.dataList = data.data.list
        this.total = data.data.total
      })
    },

    // 每页数
    sizeChangeHandle(val) {
      this.size = val
      this.page = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.page = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 修改新增弹层
    addOrUpdateHandle(id, data) {
      this.formData.id = id || 0
      if (this.formData.id) {
        // 修改
        this.formData = data
        this.visible = true
      } else {
        // 新增
        this.visible = true
      }
    },
    // 确定添加
    async dataFormSubmit() {
      if (this.formData.id) {
        // 修改
        const { content, id, imageUrl, isActive, linkUrl, title } =
          this.formData
        this.$http({
          url: this.$http.adornUrl('/sys/homepagePush/update'),
          method: 'put',
          data: { content, id, imageUrl, isActive, linkUrl, title }
        }).then(({ data }) => {
          if (data.code === 0) {
            this.$message.success(data.msg)
            this.closeForm()
            this.getDataList()
          } else {
            this.$message.error(data.msg)
          }
        })
      } else {
        this.$refs.formData.validate(async (valid) => {
          if (valid) {
            //上传图片
            let imgUrl = ''
            if (this.fileList[0]) {
              const formData = new FormData()
              formData.append('file', this.fileList[0].raw)
              const { data } = await this.$http({
                url: this.$http.adornUrl('/sys/file/addFile'),
                method: 'post',
                data: formData,
                'content-type': 'multipart/form-data'
              })
              imgUrl = data.imgUrl
            }
            this.$http({
              url: this.$http.adornUrl('/sys/homepagePush/add'),
              method: 'post',
              data: {
                ...this.formData,
                imageUrl: imgUrl
              }
            }).then(({ data }) => {
              if (data.code === 0) {
                this.$message.success(data.msg)
                this.closeForm()
                this.getDataList()
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    },
    // 关闭
    closeForm() {
      this.visible = false
      this.selectedOptions = []
      this.$refs['formData'].resetFields()
      this.formData = {}
      this.fileList = []
      this.$refs.upload.clearFiles()
    },

    // 刷新
    refresh() {
      //this.dataForm = {}
      //this.selectedOptions = []
      this.getDataList()
    },
    // 删除
    deleteHandle(id) {
      this.$confirm(`确定进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/homepagePush/delete'),
            method: 'delete',
            params: { id }
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.getDataList()
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    }
  },
  mounted() {
    this.getDataList()
  }
}
</script>

<style></style>
